package com.xunyin.modules.redisqueue;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xunyin.enums.StatusEnum;
import com.xunyin.enums.UserGradeCatchTypeEnum;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.service.CouponService;
import com.xunyin.modules.mtopengift.service.OpenGiftService;
import com.xunyin.modules.mtusergrade.domain.MtUserGrade;
import com.xunyin.modules.mtusergrade.service.UserGradeService;
import com.xunyin.modules.mtusergrade.service.mapper.MtUserGradeMapper;
import com.xunyin.modules.shareorder.service.mapper.TShareOrderMapper;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.YxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

// 消息订阅者
@Slf4j
@Component
public class MessageSubscriber implements MessageListener {

    /**
     * 卡券服务接口
     */
    @Autowired
    private CouponService couponService;

    /**
     * 开卡赠礼服务接口
     */
    @Autowired
    private OpenGiftService openGiftService;

/*    @Autowired
    private MtOpenGiftMapper mtOpenGiftMapper;*/

    @Autowired
    private MtUserGradeMapper mtUserGradeMapper;

    /**
     * 会员等级服务接口
     * */
    @Autowired
    private UserGradeService userGradeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private YxUserService yxUserService;

    @Autowired
    private TShareOrderMapper tShareOrderMapper;

    @Override
    public void onMessage(Message message, byte[] pattern) {

        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        PublishMessage publishMessage = (PublishMessage)msg;
        // 添加新注册用户赠送卡券
        if(publishMessage.getMsgType()==1){

            Integer userId = publishMessage.getUserId();
            MtCoupon coupon = new MtCoupon();
            // 是否新注册赠送，A：是；D：否
            coupon.setIsNewGive("A");
            List<MtCoupon> list = couponService.queryCouponListByCondi(coupon);
            if(list!=null && list.size()>0){
                for(MtCoupon mtCoupon:list){
                    if(mtCoupon.getStoreIds()!=null||!"".equals(mtCoupon.getStoreIds())){
                        String[] storeIds = mtCoupon.getStoreIds().split(",");
                        for(String storeId : storeIds){
                            couponService.sendCoupon(mtCoupon.getId(), 1 , userId, Integer.parseInt(storeId));
                        }
                    }
                }
            }
        // 充值升级会员等级,享受预约下单折扣,并有开卡赠礼（赠券）
        }else if (publishMessage.getMsgType()==2){

            LambdaQueryWrapper<MtUserGrade> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(MtUserGrade::getStatus, StatusEnum.ENABLED.getKey());
            lambdaQueryWrapper.orderByDesc(MtUserGrade::getId);
            List<MtUserGrade> dataList = mtUserGradeMapper.selectList(lambdaQueryWrapper);
            log.info("dataList.size():"+dataList.size());
            if(dataList!=null){
                for (MtUserGrade item : dataList) {
                    // 升级方式是充值获取的
                    if(item.getCatchType().equals(UserGradeCatchTypeEnum.RECHARGE.getKey())){
                        log.info(" openGiftService.openGift");
                        openGiftService.openGift(
                                publishMessage.getUserId(),
                                item.getId(),
                                false,
                                publishMessage.getStoreId());
                    }
                }
            }

        // 用户下单支付完成后，看是否有推荐人,判断是否为第一单
        // 如果有，看门店是否有设置推荐赠送时长券，如果有就发送一个推荐赠送的时长券给推荐人
        } else if (publishMessage.getMsgType() == 3){

            Integer userId = publishMessage.getUserId();
            YxUser yxUser = yxUserService.getById(userId);
            Long spreadUid = yxUser.getSpreadUid();
            // 表示有推荐人
            if(spreadUid.compareTo(0l) > 0){
                // 判断当前用户是否为第一单
                Integer orderCount = tShareOrderMapper.countOrderByCreadUserId(userId);
                if(orderCount == 1){

                    // 看门店是否有设置推荐赠送时长券，如果有就发送一个推荐赠送的时长券给推荐人
                    MtCoupon coupon = new MtCoupon();
                    // 是否给推荐人赠送，A：是；D：否
                    //coupon.setIsNewGive("A");
                    coupon.setRefGive("A");
                    List<MtCoupon> list = couponService.queryCouponListByCondi(coupon);
                    if(list!=null && list.size()>0){
                        for(MtCoupon mtCoupon:list){
                            if(mtCoupon.getStoreIds()!=null||!"".equals(mtCoupon.getStoreIds())){
                                String[] storeIds = mtCoupon.getStoreIds().split(",");
                                for(String storeId : storeIds){
                                    couponService.sendCoupon(mtCoupon.getId(), 1 , userId, Integer.parseInt(storeId));
                                }
                            }
                        }
                    }
                    // mt_coupon 添加推荐赠送的时长券给推荐人

                }
            }
        }
    }

}
